//
//  BTC+Account.swift
//  XHWalletUtils
//
//  Created by xinph on 2020/5/19.
//  Copyright © 2020 xinph. All rights reserved.
//

import Foundation

extension BTC: AccountProtocol {
    public static func createAccountByPrivate(_ password: String, name: String) -> coswift.Promise<WalletType> {
        let promise = coswift.Promise<WalletType>()
        
        let password = password // We recommend here and everywhere to use the password set by the user.
        let keystore: EthereumKeystoreV3
        let keyData: Data
        do {
            keystore = try EthereumKeystoreV3(password: password)!
            keyData = try JSONEncoder().encode(keystore.keystoreParams)
        } catch {
            promise.reject(error: XHError(createWalletFailure))
            return promise
        }
        let address = keystore.addresses!.first!.address
        let account = Account(name, address: address, coin: 0)
        let wallet = ETH(keystore: keyData, path: CoinBIP44.defaultBTCPath, isHD: false, privateKey: nil, publicKey: nil)
        Manager.IO.writeWallet(account, wallet: wallet)
        promise.fulfill(value: wallet)
      
        return promise
    }

    public static func importAccountByPrivate(_ password: String, name: String, private: String) -> coswift.Promise<WalletType> {
        let promise = coswift.Promise<WalletType>()
        
        guard !`private`.isEmpty else {
            promise.reject(error: XHError(privateKeyError))
            return promise
        }
        let formattedKey = `private`.trimmingCharacters(in: .whitespacesAndNewlines)
        let dataKey = Data.fromHex(formattedKey)!
        let keystore: EthereumKeystoreV3
        let keyData: Data
        do {
            keystore = try EthereumKeystoreV3(privateKey: dataKey, password: password)!
            keyData = try JSONEncoder().encode(keystore.keystoreParams)
        } catch {
            promise.reject(error: XHError(privateKeyError))
            return promise
        }
        let address = keystore.addresses!.first!.address
        let account = Account(name, address: address, coin: 0)
        let wallet = ETH(keystore: keyData, path: CoinBIP44.defaultBTCPath, isHD: false, privateKey: nil, publicKey: nil)
        Manager.IO.writeWallet(account, wallet: wallet)
        promise.fulfill(value: wallet)
       
        return promise
    }
}
